package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.redis.CacheService;
import com.heima.common.constants.ScheduleConstants;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.Taskservice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Author 刘旭
 * @Date 2022/9/3 10:49
 * @Description:
 */
@Service
public class TaskServiceImpl implements Taskservice {


    /**
     * 目前的场景，用户在提交自媒体文章到数据库中===》任务的添加
     * 添加延迟任务到数据库和redis中
     *
     * @param task 需要添加的延迟任务
     * @return 延迟任务的id
     */
    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    public long addTask(Task task) {
        //1。把任务数据储存到任务库
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        taskinfoMapper.insert(taskinfo);
        //1.1储存任务日志表（记录任何日志，仅此而已）
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo, taskinfoLogs);
        taskinfoLogs.setVersion(1);
        taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
        taskinfoLogsMapper.insert(taskinfoLogs);
        task.setTaskId(taskinfo.getTaskId());
        addTaskToCache(task);
        return taskinfo.getTaskId();
    }

    private void addTaskToCache(Task task) {
        // 1.5 记得区分任务的类型和优先级(redis的key用不同的key来存储)
        String key = task.getTaskType() + "_" + task.getPriority();
        //2.拆分任务，判断文章的发布时间,进行任务缓存的储存
        long futuretime = System.currentTimeMillis() + (5 * 60 * 1000);
        String s = JSON.toJSONString(task);
        // 2.1 判断执行时间是否小于当前时间，立即需要执行延迟任务
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            // 存储到list队列中
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, s);
            // 2.2. 判断执行时间是否小于当前时间+5分钟 未来需要执行任务
        } else if (task.getExecuteTime() <= futuretime) {
            // 存储到未来队列
            cacheService.zAdd(ScheduleConstants.FUTURE + key, s, task.getExecuteTime());
        }
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancleTask(long taskId) {
        //0参数校验
        if (taskId == 0) {
            return false;
        }
        //取消数据库任务
        //1.1修改任务日志中的任务状态
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(ScheduleConstants.CANCELLED);
        taskinfoLogsMapper.updateById(taskinfoLogs);
//        taskinfoLogsMapper.updateById(taskinfoLogs);
        //1.2删除任务表中的任务数据
        taskinfoMapper.deleteById(taskId);
        //取消redis队列中的任务

        //封装一个task对象
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        //得到key
        String key = taskinfoLogs.getTaskType() + "_" + taskinfoLogs.getPriority();
        if (taskinfoLogs.getExecuteTime().getTime() <= System.currentTimeMillis()) {
            //代表需要进行立即删除
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            //代表需要删除未来队列的数据
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
        return true;
    }

    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        //拼接redis的key值
        String key = type + "_" + priority;
        //resis出栈
        String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        //判断是否取出任务
        if (StringUtils.isNotBlank(taskJson)) {
            task = JSON.parseObject(taskJson, Task.class);
            //修改任务日志状态为执行中，删除任务表的数据
            //修改任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
            taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            //删除任务表的数据
            taskinfoMapper.deleteById(task.getTaskId());
        }
        return task;
    }

    /**
     * 把未来队列满足的数据储存到立即消费队列里
     */
    @Scheduled(cron = "* * * * * ?")
    public void refresh() {
        System.out.println("我执行了。。。" + new Date());
        Set<String> keys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        //遍历所有的key
        for (String key : keys) {
            //查询未来队列中的满足立即消费的数据
            Set<String> strings = cacheService.zRangeByScore(key, 0, System.currentTimeMillis());
            //根据未来队列key获得消费队列的key
            String topicKey = ScheduleConstants.TOPIC + key.split(ScheduleConstants.FUTURE)[1];
            //把未来队列满足的数据储存到消费队列中
            //使用redis的管道技术来优化代码”future_1_1
            if (strings.size() > 0) {
                cacheService.refreshWithPipeline(key, topicKey, strings);
            }
        }

    }

    @Scheduled(cron = "0 */5 * * * ?")
    public void relaodDb() {
        //清除redis中的队列数据
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
        //查询时间5分钟内的任务数据
        Date queryDate = new Date(new Date().getTime() + (5 * 60 * 1000));
        LambdaQueryWrapper<Taskinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(Taskinfo::getExecuteTime, queryDate);
        //代表的是《=5分钟的所有消费的数据
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(wrapper);
        //判断tasks是否存在
        if (!CollectionUtils.isEmpty(taskinfos)) {
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);

            }
        }
//        return taskinfo.get
        return;
    }

//    private void addTaskToCache(Task task) {
//
//        //记得区分任务的类型，和优先级
//        String key = task.getTaskType() + "_" + task.getPriority();
//        //拆分任务，判断文章的发布时间，进行任务缓存的储存
//        long futureTime = System.currentTimeMillis() + (5 * 60 * 1000);
//        //判断执行时间是否《=当前时间 立即需要执行延迟任务
//        if (task.getExecuteTime() <= System.currentTimeMillis()) {
//            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
//
//        } else if (task.getExecuteTime() <= futureTime) {
//            //判断执行时间是否《=的当前时间+5分钟 未来需要执行任务
//            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
//
//
//        }
//    }
}